<?php
/**
 * WP-Click-Tracker
 *
 * Contains all the click tracker functions.
 *
 * @author Eric Lamb <eric@ericlamb.net>
 * @package    wp-click-tracker
 * @version 0.4.2
 * @filesource
 * @copyright 2009 Eric Lamb.
 */
/*
Plugin Name: WP-Click-Tracker
Plugin URI: http://blog.ericlamb.net/wp-click-track/
Description: Tracks all links in posts.
Version: 0.4.2
Author: Eric Lamb
Author URI: http://blog.ericlamb.net
*/

/*  Copyright 2009  Eric Lamb  (email : eric@ericlamb.net)
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/*

URL to grab stats:
http://dashboard.wordpress.com/wp-includes/charts/stats-data.php?blog=6019810
$blog comes from stats_options in options table
*/

/**
 * Version of wp-click-tracker code
 * @global string	$click_tracker_version 
 */
$click_tracker_version = "0.4.2";

/**
 * Version of wp-click-tracker database
 * @global string	$click_tracker_db_version 
 */
$click_tracker_db_version = "0.2";

/**
 * Default number of items to display per block
 * @global int	$click_tracker_page_default 
 */
$click_tracker_page_default = 10;

/**
 * Key to use for distributed links
 * @global string	$click_tracker_dist_get 
 */
$click_tracker_dist_get = 'wp_ct';


include 'admin.inc.php';

/**
 * Wrapper for click track filter
 *
 * @param   string  $content	string to parse
 * @return  string				The completed 
 */
function wp_click_tracker_filter($content)
{
	return wp_click_tracker_replace_uris($content);
}

/**
 * Takes a string and extracts all the links (URIs)
 *
 * @param   string  $content     string to parse
 * @return  array	The links
 */
function wp_click_tracker_extract_urls($content){

	preg_match_all('/<a[^>]+>/i',$content,$links_html);
	$total = count($links_html['0']);
	$links = array();
	for($i=0;$i<$total;$i++){
		$links_html['0'][$i] = str_replace("'",'"',$links_html['0'][$i]);

		preg_match_all('/(href|title)=("[^"]*")/i',$links_html['0'][$i],$link_meta);

		$links[$i]['href'] = str_replace(array('"','\''),'',$link_meta['2']['0']);
		$links[$i]['title'] = str_replace(array('"','\''),'',$link_meta['2']['1']);

		//it's wierd; sometimes the keys on $link_meta['2'] aren't exact...
		//HACK to fix for now; sorry :(
		if(!preg_match("/http:\/\//", $links[$i]['href'])){
			$links[$i]['href'] = str_replace(array('"','\''),'',$link_meta['2']['1']);
			$links[$i]['title'] = str_replace(array('"','\''),'',$link_meta['2']['0']);
		}
	}
	return $links;
}

/**
 * Replaces all the URLs in a string with newly created URLs for tracking
 *
 * @param   string  $content	string to parse
 * @return  string	$content	The filtered content
 */
function wp_click_tracker_replace_uris($content){

	$links = wp_click_tracker_extract_urls($content);

	//print_r($links);
	//return $content;

	$_link_count = count($links);
	$_links = $links;
	$new_content = $content;
	unset($content);
	for($i=0;$i<$_link_count;$i++){

		//get rid of mailto: links
		$parse_ok = FALSE;
		if(strpos($_links[$i]['title'], 'mailto:') === FALSE && strpos($_links[$i]['href'], 'mailto:') === FALSE && strpos($_links[$i]['href'], 'javascript:') === FALSE){ #fix 0.4 for Joerg & Logan
			$parse_ok = TRUE;	
		}

		if(trim($_links[$i]['href']) == '' && trim($_links[$i]['title']) == ''){ //skip blank entries
			$parse_ok = FALSE;
		}

		if($_links[$i]['href']{0} == '#' || $_links[$i]['title']{0} == '#'){ //skip anchor links
			$parse_ok = FALSE;
		}
		
		if($parse_ok){ 
			$_new_links = $_links[$i]['href'].'" onclick="javascript:TrackClick(\''.urlencode(trim($_links[$i]['href'])).'\',\''.urlencode(trim($_links[$i]['title'])).'\')"';
			$new_content = str_replace($_links[$i]['href'].'"',$_new_links,$new_content);
			$new_content = str_replace($_links[$i]['href']."'",$_new_links,$new_content);
		}
	}

	$new_content = str_replace("href='", 'href="',$new_content);

	return $new_content;
}

include_once 'install.inc.php';

/**
 * Adds the javascript embed to the client header
 *
 * @return  void
 */
function wp_click_tracker_head(){

	//get the full URL to the site (0.4 fix)
	
	$site_url = get_option( 'siteurl' );
	//$file = plugin_basename(__FILE__);
	
	echo <<<HTML
		
	<script type="text/javascript" src="$site_url/wp-content/plugins/wp-click-track/ajax.js"></script>
	<script type="text/javascript">
		var ajax = new Array();
		function TrackClick(link,title) {

			//alert("$site_url?wp_click_tracked="+link+"***"+title+"***");
			var index = ajax.length;
			ajax[index] = new sack();		
			ajax[index].requestFile = "$site_url?wp_click_tracked="+link+"***"+title+"***";	
			ajax[index].onCompletion = null;
			ajax[index].runAJAX();
			return true;
		}
	</script>
HTML;
}

/**
 * Execution of click tracker 
 *
 * @return  void
 */
function wp_click_tracker_go(){
	global $wpdb, $click_tracker_dist_get;

	//check the GET so sites built on a sub directory get tracked (0.4 fix) 
	//$_GET[$click_tracker_dist_get] is used for distributable links
	//$_GET['wp_click_tracked'] is used for internally created links
	$forward_to_url = FALSE;
	if(isset($_GET['wp_click_tracked']) || isset($_GET[$click_tracker_dist_get])){ //looks like we have a tracking link...
		
		if(isset($_GET[$click_tracker_dist_get])){

			$link_id = (int)$_GET[$click_tracker_dist_get];
			$sql = "SELECT link_id,link_destination FROM ".$wpdb->prefix."tracking_links WHERE link_id = '".$wpdb->escape($link_id)."'";
			$result = $wpdb->get_results($sql);
			$total = count($result);
			$link_id = ($total == '1' ? $result['0']->link_id : FALSE);
			$destination = $result['0']->link_destination;
			$forward_to_url = TRUE;

			if(!$link_id){
				return FALSE;
			}

		} else {
			//convert back to normal
			$_destination = $_GET['wp_click_tracked'];
			$_destination_parts = explode('***',$_destination);

			$destination = $_destination_parts['0'];
			
			//make sure we actually have something here 
			// 0.3 BUG FIX
			if($destination == ''){
				return FALSE;
			}
			$link_title = (strlen($_destination_parts['1']) >= '1' ? $_destination_parts['1'] : 'No Title Given');
			//check to see if it's an update or an insert
			$sql = "SELECT link_id FROM ".$wpdb->prefix."tracking_links WHERE link_destination = '".$wpdb->escape($destination)."'";
			$result = $wpdb->get_results($sql);

			$total = count($result);
			$link_id = ($total == '1' ? $result['0']->link_id : FALSE);
			
			if(!$link_id){
				//insert
				$link_id = wp_click_tracker_add_link($link_title,$destination);
			}
		}

		$click_refer = $_SERVER['HTTP_REFERER'];
		$stat_ip  =  $_SERVER['REMOTE_ADDR'];

		if(isset($_COOKIE["el_$link_id"])){

			$sql = "INSERT INTO ".$wpdb->prefix."tracking_clicks SET link_id = '".$wpdb->escape($link_id)."' , click_refer = '".$wpdb->escape($click_refer)."', unique_click = '1', click_date = now(), click_ip = '".$wpdb->escape($stat_ip)."'";
			$wpdb->query($sql);

			$sql = "UPDATE ".$wpdb->prefix."tracking_links SET link_total_clicks = link_total_clicks+1  WHERE link_id = '".$wpdb->escape($link_id)."' ";
			$wpdb->query($sql);
			
		} else {

			setcookie("el_$link_id", $link_id, time()+86400);
			$sql = "UPDATE ".$wpdb->prefix."tracking_links SET link_total_clicks = link_total_clicks+1, link_unique_clicks = link_unique_clicks+1 WHERE link_id = '".$wpdb->escape($link_id)."' ";
			$wpdb->query($sql);

			$sql = "INSERT INTO ".$wpdb->prefix."tracking_clicks SET link_id = '".$wpdb->escape($link_id)."' , click_refer = '".$wpdb->escape($click_refer)."', unique_click = '0', click_date = now(), click_ip = '".$wpdb->escape($stat_ip)."'";
			$wpdb->query($sql);

		}

		if($forward_to_url && $destination){
			header("Location: $destination");
		}
		exit;
	}
	
}

/**
 * Displays administration quick view 
 *
 * @return  void
 */
function wp_click_tracker_link_data(){
	global $wpdb;

	$post_id = (isset($_REQUEST['post']) ? $_REQUEST['post'] : FALSE);

	if(!$post_id){
		return FALSE;
	}

	$sql = "SELECT post_content,post_excerpt FROM ".$wpdb->prefix."posts WHERE ID = '".$wpdb->escape($post_id)."'";
	$result = $wpdb->get_results($sql);
	$select_total = count($result);
	?>

<div id='normal-sortables' class='meta-box-sortables '>
<div id="postexcerpt" class="postbox " >
<div class="handlediv" title="Click to toggle"><br /></div><h3 class='hndle'><span>Click Tracker</span></h3>
<div class="inside">

<? 
	$post_links = wp_click_tracker_extract_urls($result['0']->post_content);
	$_check_urls = array();
	$total = count($post_links);
	for($i=0;$i<$total;$i++){
		$_check_urls[] = $wpdb->escape($post_links[$i]['href']);
	}
	$_check_urls = "'".implode("','",$_check_urls)."'";
	$sql = "SELECT link_title,link_destination,link_total_clicks,link_unique_clicks FROM ".$wpdb->prefix."tracking_links WHERE link_destination IN($_check_urls)";
	$result = $wpdb->get_results($sql);

	$select_total = count($result);
	if($select_total >= '1'){

		wp_click_track_list_links($result, $select_total, FALSE, TRUE);

	} else {

		echo 'No Links Found';
		
	}
?>
</div>
</div>

	<?
}

/**
 * Adds the click tracker options page to the administration module
 *
 * @return	void
 */
function wp_click_tracker_menu() {

	if ( function_exists('add_submenu_page') ){
		add_submenu_page('plugins.php', __('Click Tracker'), __('Click Tracker'), 8, __FILE__, 'wp_click_tracker_admin_module');
	}
	add_options_page('Click Tracker Options', 'Click Tracker', 8, __FILE__, 'wp_click_tracker_options');
}

/**
 * Displays the click tracker options module
 *
 * @return  void
 */
function wp_click_tracker_options(){
	global $click_tracker_page_default;

	$plugin_data = get_plugin_data(__FILE__);
	$plugin_options = get_option('click_tracker');
	$default = $click_tracker_page_default;
	$form_updated = FALSE;
	$page = (isset($_REQUEST['page']) ? $_REQUEST['page'] : FALSE);

	if(isset($_POST['go']) && $_POST['go'] == 'yes'){
		
		
		$plugin_options['parse_the_content'] = (isset($_POST['parse_the_content']) && $_POST['parse_the_content'] == '1' ? $_POST['parse_the_content'] : '0');
		$plugin_options['parse_archive'] = (isset($_POST['parse_archive']) && $_POST['parse_archive'] == '1' ? $_POST['parse_archive'] : '0');
		$plugin_options['parse_blog_roll'] = (isset($_POST['parse_blog_roll']) && $_POST['parse_blog_roll'] == '1' ? $_POST['parse_blog_roll'] : '0');
		$plugin_options['parse_comment_author_link'] = (isset($_POST['parse_comment_author_link']) && $_POST['parse_comment_author_link'] == '1' ? $_POST['parse_comment_author_link'] : '0');
		$plugin_options['parse_the_excerpt'] = (isset($_POST['parse_the_excerpt']) && $_POST['parse_the_excerpt'] == '1' ? $_POST['parse_the_excerpt'] : '0');
		$plugin_options['parse_the_meta'] = (isset($_POST['parse_the_meta']) && $_POST['parse_the_meta'] == '1' ? $_POST['parse_the_meta'] : '0');
		$plugin_options['parse_comment_text'] = (isset($_POST['parse_comment_text']) && $_POST['parse_comment_text'] == '1' ? $_POST['parse_comment_text'] : '0');
		

		$plugin_options['click_count'] = (isset($_POST['click_count']) ? $_POST['click_count'] : $default);
		$plugin_options['link_list_count'] = (isset($_POST['link_list_count']) ? $_POST['link_list_count'] : $default);
		$plugin_options['referrer_count'] = (isset($_POST['referrer_count']) ? $_POST['referrer_count'] : $default);

		update_option('click_tracker', $plugin_options);
		$plugin_options = get_option('click_tracker');
		$form_updated = TRUE;
	}

	?>
	<div class="wrap" id="sm_div">
		<form method="post" action="<?=$_SERVER['PHP_SELF']; ?>?page=<?=$_REQUEST['page'];?>">
		<div id="icon-options-general" class="icon32"><br /></div>

			<h2>Configure <?php echo $plugin_data['Name']; ?> <?php echo $plugin_data['Version']; ?></h2>

			<?php 
			if($form_updated){
				wp_click_track_admin_message( __($plugin_data['Name'].' settings updated!','default'));
			}
			echo '<div align="right"> <a href="'.dirname($_SERVER['PHP_SELF']).'/plugins.php?page='.$page.'" class="button">'.__('View Links').'</a> <a href="'.dirname($_SERVER['PHP_SELF']).'/plugins.php?page='.$page.'&req=add" class="button">'.__('Add Link').'</a></div>';
			?>

			<h3>Parse Settings</h3>
			<p>You can set <?php echo $plugin_data['Name']; ?> to automatically parse your posts and convert all links to click trackable links. It's pretty memory intensive and rigid though, so if you have poorly formed links it may cause your Wordpress setup to become unstable (it's still a beta afterall :). </p>
			
			<p>You can choose the individual areas you want to convert below: </p>

			<table class="form-table">
			<tr valign="top">
			<th scope="row">Post</th>
			<td><label for="parse_the_content"><input name="parse_the_content" type="checkbox" id="parse_the_content" value="1"  <?php echo ($plugin_options['parse_the_content'] == '1' ? 'checked="checked"' : ''); ?> />Parse the actual content of a post. </label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Post Excerpt</th>
			<td><label for="parse_the_excerpt"><input name="parse_the_excerpt" type="checkbox" id="parse_the_excerpt" value="1"  <?php echo ($plugin_options['parse_the_excerpt'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links used in the excerpt portion of posts</label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Post Meta</th>
			<td><label for="parse_the_meta"><input name="parse_the_meta" type="checkbox" id="parse_the_meta" value="1"  <?php echo ($plugin_options['parse_the_meta'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links used in the meta portion of posts</label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Comment Body</th>
			<td><label for="parse_comment_text"><input name="parse_comment_text" type="checkbox" id="parse_comment_text" value="1"  <?php echo ($plugin_options['parse_comment_text'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links used in post comments</label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Comment Author Link</th>
			<td><label for="parse_comment_author_link"><input name="parse_comment_author_link" type="checkbox" id="parse_comment_author_link" value="1"  <?php echo ($plugin_options['parse_comment_author_link'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links used in the comment author name (in comments) </label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Archive Widget</th>
			<td><label for="parse_archive"><input name="parse_archive" type="checkbox" id="parse_archive" value="1"  <?php echo ($plugin_options['parse_archive'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links displayed in the Archive Sidebar Widget </label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Blog Roll Widget</th>
			<td><label for="parse_blog_roll"><input name="parse_blog_roll" type="checkbox" id="parse_blog_roll" value="1"  <?php echo ($plugin_options['parse_blog_roll'] == '1' ? 'checked="checked"' : ''); ?> />Parse the links displayed in the Blog Roll Sidebar Widget </label></td>
			</tr>
			</table>

			<h3>Admin Limits</h3>
			<p>Choose how many items you want displayed in the admin for <?php echo $plugin_data['Name']; ?>. This REALLY helps when you have a lot of items to display.</p>

			<p>NOTE: Anything but a positive number will result in the default of <?php $default; ?> being used.</p>

			<table class="form-table">
			<tr valign="top">
			<th scope="row">Referrer Count</th>
			<td><label for="referrer_count"><input name="referrer_count" type="text" id="referrer_count" value="<?php echo $plugin_options['referrer_count']; ?>" class="small-text" /></label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Click Count</th>
			<td><label for="click_count"><input name="click_count" type="text" id="click_count" value="<?php echo $plugin_options['click_count']; ?>" class="small-text" /></label></td>
			</tr>

			<tr valign="top">
			<th scope="row">Link List Count</th>
			<td><label for="link_list_count"><input name="link_list_count" type="text" id="link_list_count" value="<?php echo $plugin_options['link_list_count']; ?>" class="small-text" /></label></td>
			</tr>
			</table>


			<p class="submit">
				<input type="submit" name="Submit" class="button-primary" value="Save Changes" />
			</p>

			<input type="hidden" name="go" value="yes" \>

		</form>
	</div>

	<?
}

/**
 * Displays the click tracker administration module
 *
 * @return  void
 */
function wp_click_tracker_admin_module() {
	global $click_tracker_db_version,$wpdb,$link_page_total;
	$new_version = TRUE;
	$plugin_data = get_plugin_data(__FILE__);
	$current = get_option( 'update_plugins' );

	if (!current_user_can('manage_links'))
		wp_die(__("You do not have sufficient permissions to edit the links for this blog."));

	$req = (isset($_REQUEST['req']) ? $_REQUEST['req'] : FALSE);
	$link_id = (isset($_REQUEST['link']) ? (int)$_REQUEST['link'] : FALSE);
	$page = (isset($_REQUEST['page']) ? $_REQUEST['page'] : FALSE);
	$paged = (isset($_REQUEST['paged']) ? (int)$_REQUEST['paged'] : '1');
	$ref_paged = (isset($_REQUEST['ref_paged']) ? (int)$_REQUEST['ref_paged'] : '1');
	$ref_paged = (isset($_REQUEST['ref_paged']) ? (int)$_REQUEST['ref_paged'] : '1');
	$ip_addr = (isset($_REQUEST['ip']) && long2ip($_REQUEST['ip']) ? long2ip($_REQUEST['ip']) : FALSE);

	$file = plugin_basename(__FILE__);
	?>
<div class="wrap" id="sm_div">
	<form method="post" action="<?=$_SERVER['PHP_SELF']; ?>?page=<?=$_REQUEST['page'];?>">
	<div id="icon-link-manager" class="icon32"><br /></div>
		<h2><?php echo $plugin_data['Name']; ?> <?php echo $plugin_data['Version']; ?></h2>
	<? 

	//check if an update has been issued
	if(isset($current->response[$file])) {
		$r = $current->response[$file];
		if ( !current_user_can('edit_plugins') || version_compare($wp_version,"2.5","<") ) {
			wp_click_track_admin_message( __('There is a new version of '.$plugin_data['Name'].' available. <a href="'.$r->url.'">Download version '.$r->new_version.' here</a>.','default'));
		} elseif ( empty($r->package) ) {
			wp_click_track_admin_message( __('There is a new version of '.$plugin_data['Name'].' available. <a href="'.$r->url.'">Download version '.$r->new_version.' here</a> <em>automatic upgrade unavailable for this plugin</em>.','default'));
		} else {
			wp_click_track_admin_message( __('There is a new version of '.$plugin_data['Name'].' available. <a href="'.$r->url.'">Download version '.$r->new_version.' here</a> or <a href="'.wp_nonce_url("update.php?action=upgrade-plugin&amp;plugin=$file", 'upgrade-plugin_' . $file).'">upgrade automatically</a>.','default'));
		}
	}

	//check if the blog has GoogleAnalyticsPP
	//warn about incompatibility...
	$google_options = get_option('GoogleAnalyticsPP');
	if(isset($google_options['trackoutbound']) && $google_options['trackoutbound'] == '1'){
		wp_click_track_admin_message( __('It looks like you have Google Analytics for WordPress installed with Track Outbound links enabled. This can cause issues with '.$plugin_data['Name'].' '.$plugin_data['Version'].'. </p><p>Click <a href="'.$_SERVER['PHP_SELF'].'?page='.$_REQUEST['page'].'&req=ga_outbound">here</a> to disable.','default'));
	}

	if(isset($_REQUEST['msg'])){

		switch($_REQUEST['msg']){

			case 'success_add':
				wp_click_track_admin_message( __('Link Added','wp_click_tracker'));
			break;

			case 'success_update':
				wp_click_track_admin_message( __('Link Modified','wp_click_tracker'));
			break;

			case 'fail_update':
				wp_click_track_admin_message( __('Couldn\'t Update Link','wp_click_tracker'));
			break;

		}
	}

	
	echo '<div align="right">';

	if($link_id || $req == 'add' || $req == 'edit'){
		echo ' <a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'" class="button">'.__('List Links').'</a> ';
	}

	if($link_id && $req != 'edit'){
		echo ' <a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'&link='.$link_id.'&req=edit" class="button">'.__('Edit Link').'</a>';
	}

	if($link_id && $req == 'edit' || $ip_addr){
		echo ' <a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'&link='.$link_id.'" class="button">'.__('Back to Link').'</a>';
	}

	echo ' <a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'&req=add" class="button">'.__('Add Link').'</a> <a href="'.dirname($_SERVER['PHP_SELF']).'/options-general.php?page='.$page.'" class="button">'.__('Configure').'</a></div>';

	switch($req){

		case 'ga_outbound':
			$options = get_option('GoogleAnalyticsPP');
			$options['trackoutbound'] = 0;
			update_option('GoogleAnalyticsPP', $options);
		break;

		case 'add':
			
			echo '<h3>Add Click Track Link</h3>';
			wp_click_track_mod_link_form(FALSE,$req);

		break;

		case 'edit':

			echo '<h3>Edit Click Track Link</h3>';
			wp_click_track_mod_link_form($link_id, $req);

		break;

		default:
				
			if($link_id){
				
				if($ip_addr){

					wp_click_track_admin_list_ip_page($ip_addr, $link_id, $req, $page, $paged, $ref_paged);

				} else {

					wp_click_track_admin_list_link_page($link_id, $req, $page, $paged, $ref_paged);
				}

			} else {

				wp_click_track_admin_list_links($req, $page, $paged, $ref_paged);

			}

		break;
	}
}

/**
 * Returns the clicks 
 *
 * @param   string  $BuildWhere	customize sql
 * @return  object
 */
function wp_click_track_get_clicks($BuildWhere){
	global $wpdb;

	$sql = "SELECT * FROM ".$wpdb->prefix."tracking_clicks ".$BuildWhere;
	$result = $wpdb->get_results($sql);
	return $result;
}

/**
 * Returns the links 
 *
 * @param   string  $BuildWhere	customize sql
 * @return  object
 */
function wp_click_track_get_link_data($BuildWhere){
	global $wpdb;

	$sql = "SELECT * FROM ".$wpdb->prefix."tracking_links ".$BuildWhere;
	$result = $wpdb->get_results($sql);
	return $result;
}

/**
 * Wrapper for modifying link form processing
 *
 * @return  void
 */
function wp_click_tracker_mod_go(){
	global $wpdb;

	if(isset($_POST['mod_wpct_link'])){ //check the form...
		$errors = wp_click_track_validate_mod_link($_POST);

		if(count($errors) == '0') {

			if(isset($_POST['link'])){

				$link = (int)$_POST['link'];
				$link_data = wp_click_track_get_link_data(" WHERE link_id = '".$wpdb->escape($link)."'");
				$msg = 'fail_update';

				if(count($link_data) == '1'){

					$title = $_POST['link_name'];
					$dest = $_POST['link_destination'];
					$sql = "UPDATE ".$wpdb->prefix."tracking_links SET link_title = '".$wpdb->escape($title)."', link_destination = '".$wpdb->escape($dest)."' WHERE link_id = '".$wpdb->escape($link)."'";
					$wpdb->query($sql);
					$msg = 'success_update';
				}

			} else {

				$title = $_POST['link_name'];
				$dest = $_POST['link_destination'];
				$link = wp_click_tracker_add_link($title,$dest);
				$msg = 'success_add';
			}

			header('Location: '.$_SERVER['PHP_SELF'].'?page='.$_REQUEST['page'].'&link='.$link.'&msg='.$msg);
			exit;
		} else {
			return FALSE;
		}
	}
}

function wp_click_tracker_add_link($link_title,$destination){
	global $wpdb;

	$sql = "INSERT INTO ".$wpdb->prefix."tracking_links SET last_modified = now(), creation_date = now(), link_title = '".$wpdb->escape($link_title)."', link_desc = '', link_destination = '".$wpdb->escape($destination)."', link_total_clicks = '0', link_unique_clicks = '0'";
	$wpdb->query($sql);
	$link_id = $wpdb->insert_id;

	return $link_id;
}

register_activation_hook(__FILE__,'wp_click_tracker_install');
register_deactivation_hook(__FILE__, 'wp_click_tracker_deactivate');

add_action('edit_form_advanced', 'wp_click_tracker_link_data');
add_action('edit_page_form', 'wp_click_tracker_link_data');
//add_action('edit_link_form', 'wp_click_tracker_link_data');

add_action('admin_head', 'wp_click_tracker_admin_head');
add_action('admin_menu', 'wp_click_tracker_menu');

add_action('wp_head', 'wp_click_tracker_head');
add_action('init','wp_click_tracker_go');
add_action('admin_init','wp_click_tracker_mod_go');

$ct_options = get_option('click_tracker');
if(array_key_exists('parse_archive',$ct_options) && $ct_options['parse_archive'] == '1'){
	add_filter('get_archives_link', 'wp_click_tracker_filter', 1);
}

if(array_key_exists('parse_blog_roll',$ct_options) && $ct_options['parse_blog_roll'] == '1'){
	add_filter('wp_list_bookmarks', 'wp_click_tracker_filter', 1);
}

if(array_key_exists('parse_comment_author_link',$ct_options) && $ct_options['parse_comment_author_link'] == '1'){
	add_filter('get_comment_author_link', 'wp_click_tracker_filter', 1);
}

if(array_key_exists('parse_the_excerpt',$ct_options) && $ct_options['parse_the_excerpt'] == '1'){
	add_filter('the_excerpt', 'wp_click_tracker_filter', 1);
}

if(array_key_exists('parse_the_content',$ct_options) && $ct_options['parse_the_content'] == '1'){
	add_filter('the_content', 'wp_click_tracker_filter', 1);
}

if(array_key_exists('parse_the_meta',$ct_options) && $ct_options['parse_the_meta'] == '1'){
	add_filter('the_meta_key', 'wp_click_tracker_filter', 1); #0.3 Adds to the_meta values
}

if(array_key_exists('parse_comment_text',$ct_options) && $ct_options['parse_comment_text'] == '1' && strpos($_SERVER['PHP_SELF'], 'wp-admin') === FALSE){
	add_filter('comment_text', 'wp_click_tracker_filter', 9);
}
unset($ct_options);

include_once 'contextual_help.php';
add_action('wp_dashboard_setup', 'wp_click_track_admin_add_dashboard_widgets' );

//add_filter('link_category', 'wp_click_tracker_filter', 9); #0.2.1
//add_filter('author_feed_link', 'wp_click_tracker_filter', 9); #0.3 Adds to the_meta values
//add_filter('the_title', 'wp_click_tracker_filter', 9); #0.3 Adds to the_meta values